<template>
  <div class="top">
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img :src="image" />
      </van-swipe-item>
    </van-swipe>
  </div>
  <div class="top">
    <van-cell-group>
      <van-field v-model="user.name" label="用户名" placeholder="请输入用户名" />
      <van-field v-model="user.password" label="密码" placeholder="请输入密码" type="password"/>
    </van-cell-group>
  </div>
  <div>
    <van-button plain type="primary" color="gray" @click="clickButton(1)" style="margin-right: 1rem">登录</van-button>
    <van-button plain type="primary" color="gray" @click="clickButton(0)">清空</van-button>
  </div>
</template>
<script lang="ts">
import {defineComponent, getCurrentInstance, reactive} from 'vue';
export default defineComponent({
  name: 'Login',
  setup() {
    const {proxy}: any = getCurrentInstance()
    const images = reactive([
      'https://file.xdclass.net/video/2021/1-lbt/VIP/vip1299.png',
      'https://file.xdclass.net/video/2021/62-paas/lbt-paas.png',
      'https://file.xdclass.net/video/2021/59-Postman/59lbt.png'
    ])
    const user = reactive({
      name: '',
      password: ''
    })
    function clickButton(value: any) {
      if(user.name === '' || user.password === '') {
        proxy.$toast.fail('账号和密码不能为空')
      } else if (value === 1){
        toLogin()
      } else {
        user.name = ''
        user.password = ''
      }
    }
    // 发送登录请求
    function toLogin() {
      proxy.$http.post(`/api/login`, {
        name: user.name,
        password: user.password
      }).then((res: any) => {
        if(res.data.code === 1) {
            proxy.$toast.success('登录成功')
            window.sessionStorage.setItem('token', res.data.data.token)
            proxy.$router.push('/home')
        } else {
          proxy.$toast.fail('登录失败')
        }
      }).catch((error: any) => {
        console.log(error)
      })
    }
    return {
      images,
      user,
      clickButton
    }
  }
})
</script>
<style scoped>
img {
  width: 100%;
}
.top {
  margin-bottom: 2rem;
}
</style>